# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(NormalizeMets)
library(tidyverse)

option_list <- list(
  make_option("--t", default = "normal", type = "character", help = "normal method"),
  make_option("--ir", default = "", type = "character", help = "inner nomal meta name"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read_tsv(opt$config) %>%
  set_colnames(c("arg", "value"))

configData

isLoess <- configData["isLoess", "value"] == "T"

if (!isLoess) {
  quit(status = 0)
}

data <- read_csv("02_AllMet_Raw_Missing_Value_Filled.csv")

featureData <- data %>%
  gather("SampleID", "Value", -Raw_Metabolite, factor_key = T) %>%
  spread(Raw_Metabolite, "Value") %>%
  column_to_rownames("SampleID")

head(featureData)

sampleData <- read_csv(opt$g) %>%
  select(c("SampleID", "ClassNote")) %>%
  rename(class = ClassNote) %>%
  arrange(factor(SampleID, levels = rownames(featureData))) %>%
  mutate(batch = 1, order = 1:n()) %>%
  mutate(class = str_replace(class, "QC", "0")) %>%
  column_to_rownames("SampleID")

head(sampleData)

Norm_rlsc <- NormQcsamples(featureData, sampleData, lg = FALSE, span = 0.75)

Norm_rlsc

rownames(featureData)

head(data)

outData <- Norm_rlsc$featuredata %>%
  as_tibble() %>%
  mutate(SampleID = rownames(featureData)) %>%
  mutate(SampleID = factor(SampleID, levels = unique(SampleID))) %>%
  gather("Raw_Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value") %>%
  mutate(Raw_Metabolite=data$Raw_Metabolite)

head(outData)

write.csv(outData, "03_AllMet_Raw_NormQCsamples.csv", row.names = F)



